package joelwilson;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.junit.Assert;
import org.junit.Test;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

public class VerifyJUnitGAEDevServer extends GAETestCase {
	
	
	@Test
	public void testDatastoreConnection() throws Exception {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Transaction trx = datastore.beginTransaction();
		if (trx != null && trx.isActive()) trx.rollback();
	}
	
	@Test
	public void testMemcache() throws Exception {
		MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
		Assert.assertNotNull(memcache.getStatistics());
	}
	
	@Test
	public void testStorageSizeLimits() throws Exception {
		// build a key with a really long name
		int keyNameLength = 250;
		char character = 'a';
		StringBuilder builder = new StringBuilder(keyNameLength);
		for (int i = 0; i < keyNameLength; i++) builder.append(character++);
		
		// generate a random byte array
		byte[] rawBytes = new byte[1000000];
		Random rand = new Random();
		rand.nextBytes(rawBytes);
		
		// get the service interfaces
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
		
		// build an array of the entities
		long byteSize = 0l;
		Key key = KeyFactory.createKey("Lucene", builder.toString());
		List<Entity> entities = new ArrayList<Entity>(100);
		Entity entity = new Entity(key); 
		entity.setUnindexedProperty("file", new Blob(rawBytes));
		entities.add(entity);
		for (int i = 1; i <= 100; i++) {
			//key = key.getChild("Lucene", i);
			entity = new Entity(key.getChild("Lucene", i));
			entity.setUnindexedProperty("file", new Blob(rawBytes));
			entities.add(entity);
			byteSize += rawBytes.length;
		}
		
		// put the data into the datastore
		Transaction trx = datastore.beginTransaction();
		for (Entity en : entities) {
			datastore.put(trx, en);
		}
		trx.commit();
		
		// put the data into memcache too
		for (Entity en : entities)
			memcache.put(en.getKey(), en);
		
		// show how much we just stored, which could represent a single
		// file that was split up into several pieces.
		System.out.println("Bytes Saved to EntityGroup: " + byteSize);		
	}
}
